package com.abbas.abchat.activity;

import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;

import com.abbas.abchat.AbChatApplication;
import com.abbas.abchat.R;
import com.abbas.abchat.adapter.SearchAccountListAdapter;
import com.abbas.abchat.dao.AccountDao;
import com.abbas.abchat.dao.ChatTableDao;
import com.abbas.abchat.dao.impl.AccountDaoImpl;
import com.abbas.abchat.dao.impl.ChatTableDaoImpl;
import com.abbas.abchat.entity.Account;
import com.abbas.abchat.entity.ChatTable;

import java.util.ArrayList;
import java.util.List;

public class SearchAccountResultActivity extends BaseActivity {

    private String targetAccount;

    private AccountDao accountDao;
    private ChatTableDao chatTableDao;

    private ImageButton ibBack;
    private ListView lvResult;

    private List<Account> accounts = new ArrayList<>();

    private SearchAccountListAdapter accountListAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_result;
    }

    @Override
    protected void init() {
        targetAccount = getIntent().getStringExtra("target");
        accountDao = new AccountDaoImpl(this);
        chatTableDao = new ChatTableDaoImpl(this, AbChatApplication.getAccount().getChatTableDbName());

        ibBack = (ImageButton) findViewById(R.id.ib_back);
        lvResult = (ListView) findViewById(R.id.lv_result);

        List<ChatTable> people = null;

        try {
            people = chatTableDao.findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Account account = null;
        List<Account> findByNameAccounts = null;
        try {
            account = accountDao.findByAccount(targetAccount);
            findByNameAccounts = accountDao.findByNickName(targetAccount);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (account != null) {
            accounts.add(account);
            lvResult.setVisibility(View.VISIBLE);
        }

        if (findByNameAccounts != null && findByNameAccounts.size() > 0){
            accounts.addAll(findByNameAccounts);
            lvResult.setVisibility(View.VISIBLE);
        }

        if (accounts.size() == 0) showMessage("未找到包含关键词的账号");

        accountListAdapter = new SearchAccountListAdapter(this, chatTableDao, accounts);
        if (people != null && people.size() > 0) {
            accountListAdapter.setPeople(people);
        }
        lvResult.setAdapter(accountListAdapter);
    }

    @Override
    protected void initEvent() {

    }
}